#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/time.h>
#include <signal.h>
#include <string.h>

#include "thread.h"

void timer_handler() {
    printf("timer handler (1sec)\n");
    thread_yield();
}

static void * threadfunc(void * arg)
{
    struct sigaction sa;
    memset (&sa, 0, sizeof (sa)); 
    sa.sa_handler = &timer_handler; 
    sigaction (SIGVTALRM, &sa, NULL); 

    struct itimerval *value = malloc(sizeof(struct itimerval));
    value->it_interval.tv_sec = 1;
    value->it_value.tv_sec = 1;
    setitimer (ITIMER_VIRTUAL, value, NULL);

    char *name = arg;

    int i;
    for (i=0; i<1000000000; i++) {
        if (i%100000000 == 0) {
            printf("%s\n", name);
        }
    }
}

int main(void)
{
    thread_t thread1, thread2, thread3;
    void *retval1, *retval2, *retval3;
    int err;

    init();

    err = thread_create(&thread1, threadfunc, "1");
    assert(!err);
    err = thread_create(&thread2, threadfunc, "\t2");
    assert(!err);
    err = thread_create(&thread3, threadfunc, "\t\t3");
    assert(!err);
    
    err = thread_join(thread2, &retval2);
    assert(!err);
    err = thread_join(thread1, &retval1);
    assert(!err);
    err = thread_join(thread3, &retval3);
    assert(!err);
    
    return EXIT_SUCCESS;
}
